import datetime
import json
import re


from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

# Create your views here.
from lovehome_pro.utils.Loginmixin import LoginMixin
from Leisuerly.uitls import get_FileSize
from xyuzi.models import User, Order, HouseImage, House
from django.contrib.auth import login, authenticate
from lovehome_pro.libs.qiniuyun.qiniu_storage import storage


# class Countregister(view):
#
#     def get(self, request, mobile):
#
#         try:
#             count = User.objects.filter(mobile=mobile).count()
#         except Exception:
#             return JsonResponse({'code':400,
#                                  'errmsg':'访问数据库失败'})
#
#         if count > 0:
#             return JsonResponse({'code': 400,
#                             'errmsg': '手机重复'})
#
#         return JsonResponse({'code': 0,
#                             'errmsg': 'ok'})


class Register(View):
    # 注册页面

    def post(self, request):

        dict = json.loads(request.body.decode())

        mobile = dict.get('mobile')

        phonecode = dict.get('phonecode')

        password = dict.get('password')

        password2 = dict.get('password2')

        if not all([mobile, phonecode, password, password2]):
            return JsonResponse({'errno': '400',
                                 'errmsg':'缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': '400',
                                 'errmsg': 'mobile格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': '400',
                                 'errmsg': 'password格式有误'})
        if password != password2:
            return JsonResponse({'errno': '400',
                                 'errmsg': '两次输入不对'})

        redis_connt = get_redis_connection('verify_code')

        phonecode_server = redis_connt.get('sms_%s' % mobile)

        if not phonecode_server:
            return JsonResponse({'errno': '400',
                                 'errmsg': '短信验证码过期'})

        if phonecode != phonecode_server.decode():
            return JsonResponse({'errno': '400',
                                'errmsg': '验证码有误'})

        try:
            user = User.objects.create_user(mobile=mobile,
                                                password=password,
                                                username=mobile)
        except Exception as e:
            return  JsonResponse({'errno': '400',
                                  'errmsg': '用户信息保存失败'})
        login(request, user)

        return JsonResponse({"errno": '0',
                            "errmsg": '注册成功'})


class Modifyusername(LoginMixin, View):
    # 用户名修改

    def put(self, request):

        dict = json.loads(request.body.decode())
        username = dict.get('name')

        if not all(username):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        if request.user.username == username:

            return JsonResponse({'errno': '400',
                                 'errmsg': '和原来用户名重复请重新修改'})

        try:
            User.objects.filter(id=request.user.id).update(username=username)

        except Exception as e:
            return JsonResponse({'errno': '400',
                                 'errmsg': '数据保存失败'})

        return JsonResponse({"errno": '0',
                            "errmsg": '修改成功'})


class Listingpicture(LoginMixin, View):
    # 上传房源图片

    def post(self, request, house_id):
        file = request.FILES.get('house_image')
        if not file:
            return JsonResponse({
                'errno': '400',
                'errmsg': '缺少图片数据'
            })
        f = get_FileSize(file)
        token = storage(f)
        url = "http://qa77xtdyw.bkt.clouddn.com/"
        image = url + token
        data = {}
        data['url'] = image
        try:
            HouseImage.objects.create(url=token, house_id=house_id)

        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '数据库出错'
            })
        try:
            House.objects.filter(id=house_id).update(index_image_url=token)
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '数据库出错'
            })


        return JsonResponse({
            'data': data,
            'errno': '0',
            'errmsg': '图片上传成功',
        })

class Acceptrejectorder(LoginMixin, View):
    # 接单和拒单

    def put(self, request, order_id):
        dict = json.loads(request.body.decode())
        action = dict.get('action')
        reason = dict.get('reason')

        if not all(action):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        if action == 'accept':
            try:
                order = Order.objects.filter(id=order_id).update(status=Order.ORDER_STATUS.get('WAIT_COMMENT'))
                return JsonResponse({"errno": '0',
                             "errmsg": '操作成功'})

            except Exception as e:
                return JsonResponse({'errno': '400',
                                     'errmsg':'获取数据库失败'})


        if not all(reason):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        try:
            Order.objects.filter(id=order_id).update(status=Order.ORDER_STATUS.get('REJECTED'), comment=reason)
        except Exception as e:
            return JsonResponse({'errno': '400',
                                 'errmsg': '修改数据库失败'})

        return JsonResponse({"errno": '0',
                             "errmsg": '操作成功'})

